package com.kbbywyclient.app;

import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.multidex.MultiDex;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import com.kbbywyclient.BuildConfig;
import com.kbbywyclient.R;
import com.kbbywyclient.callback.WeChatPayCallback;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.AppModule;
import com.kbbywyclient.di.DaggerAppComponent;
import com.kbbywyclient.di.NetworkModule;
import com.kbbywyclient.ui.activity.CustomerTableActivity;
import com.kbbywyclient.ui.activity.LoginActivity;
import com.kbbywyclient.ui.activity.MatchTableActivity;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.FileUtils;
import com.kbbywyclient.util.GalleryFinalUtil;
import com.kbbywyclient.util.LogUtil;
import com.kbbywyclient.util.PhoneInfoUtil;
import com.kbbywyclient.util.pre.PreUtils;
import com.tencent.tinker.loader.app.ApplicationLike;
import com.tinkerpatch.sdk.TinkerPatch;
import com.tinkerpatch.sdk.loader.TinkerPatchApplicationLike;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.common.UmLog;
import com.umeng.message.entity.UMessage;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import java.util.HashMap;

import me.leolin.shortcutbadger.ShortcutBadger;

/**
 * Created by FHW
 * on 2017/3/21
 */

public class App extends Application {

    private static App sInstance;
    private AppComponent mAppComponent;

    private static boolean isDebug = BuildConfig.LOG_DEBUG;

    public static final String UPDATE_STATUS_ACTION = "com.umeng.message.example.action.UPDATE_STATUS";
    private Handler handler;
    public static String mDeviceToken = "";

    private Tracker mTracker;

//    public static AMapLocationClient mLocationClient = null;
//    public  AMapLocationClientOption mLocationOption = null;

    private int badgeCount = 1;//角标红点

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        App.sInstance = this;

        setupCompoent();

        LogUtil.init(isDebug);
//        LogUtil.init(true);

        //配置友盟
        //参数1:上下文，必须的参数，不能为空
        //参数2:友盟 app key，非必须参数，如果Manifest文件中已配置app key，该参数可以传空，则使用Manifest中配置的app key，否则该参数必须传入
        //参数3:友盟 channel，非必须参数，如果Manifest文件中已配置channel，该参数可以传空，则使用Manifest中配置的channel，否则该参数必须传入
        //参数4:设备类型，必须参数，传参数为UMConfigure.DEVICE_TYPE_PHONE则表示手机；传参数为UMConfigure.DEVICE_TYPE_BOX则表示盒子；默认为手机
        //参数5:Push推送业务的secret，需要集成Push功能时必须传入Push的secret，否则传空
        UMConfigure.init(sInstance,
                "58f84f5907fe650b2500045a",
                PhoneInfoUtil.getApkChannelName(sInstance),
                UMConfigure.DEVICE_TYPE_PHONE,
                "7a68845d19379e110eb742c49f1bba38");

        GalleryFinalUtil.init(this);

        FileUtils.init();

        Config.DEBUG = isDebug;
        UMShareAPI.get(this);
        //各个平台的配置
        //微信
        PlatformConfig.setWeixin("wxa6a9db829aa7e661", "d4624c36b6795d1d99dcf0547af5443d");  //
        //新浪微博
        PlatformConfig.setSinaWeibo("122307419", "fe7eab4de7c4fe159594591a7770bfdf", "http://sns.whalecloud.com/sina2/callback");//需要在友盟开发平台上绑定
        //QQ
        PlatformConfig.setQQZone("1103425657","PaanjAY5JlSCjbzE");
        //友盟推送
        initUmengPush();

        // Set the dispatch period in seconds.
        GoogleAnalytics.getInstance(this).setLocalDispatchPeriod(1);

        initTinkerPatch();

    }

    private void setupCompoent() {
        mAppComponent = DaggerAppComponent.builder()
                .appModule(new AppModule(this))
                .networkModule(new NetworkModule())
                .build();
    }

    public static App getInstance() {
        return sInstance;
    }

    public AppComponent getAppComponent() {
        return mAppComponent;
    }

    public WeChatPayCallback weChatPayCallback;

    /**
     * umeng push
     */
    private void initUmengPush() {
        PushAgent mPushAgent = PushAgent.getInstance(this);
        mPushAgent.setDebugMode(isDebug);
        handler = new Handler();

        //sdk开启通知声音
        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);
        // sdk关闭通知声音
//		mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
        // 通知声音由服务端控制
//		mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER);

//		mPushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
//		mPushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);

        mPushAgent.setDisplayNotificationNumber(5);

        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            /**
             * 自定义消息的回调方法
             * */
            @Override
            public void dealWithCustomMessage(final Context context, final UMessage msg) {

                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        // 对自定义消息的处理方式，点击或者忽略
                        boolean isClickOrDismissed = true;
                        if (isClickOrDismissed) {
                            //自定义消息的点击统计
                            UTrack.getInstance(getApplicationContext()).trackMsgClick(msg);
                        } else {
                            //自定义消息的忽略统计
                            UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg);
                        }
                        Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
                    }
                });
            }

            /**
             * 自定义通知栏样式的回调方法
             * */
            @Override
            public Notification getNotification(Context context, UMessage msg) {
                ShortcutBadger.applyCount(context, badgeCount++); //for 1.1.4+
                switch (msg.builder_id) {
                    case 1:
                        Notification.Builder builder = new Notification.Builder(context);
                        RemoteViews myNotificationView = new RemoteViews(context.getPackageName(), R.layout.notification_view);
                        myNotificationView.setTextViewText(R.id.notification_title, msg.title);
                        myNotificationView.setTextViewText(R.id.notification_text, msg.text);
                        myNotificationView.setImageViewBitmap(R.id.notification_large_icon, getLargeIcon(context, msg));
                        myNotificationView.setImageViewResource(R.id.notification_small_icon, getSmallIconId(context, msg));
                        builder.setContent(myNotificationView)
                                .setSmallIcon(getSmallIconId(context, msg))
                                .setTicker(msg.ticker)
                                .setAutoCancel(true);

                        return builder.getNotification();
                    default:
                        //默认为0，若填写的builder_id并不存在，也使用默认。
                        return super.getNotification(context, msg);
                }
            }
        };
        mPushAgent.setMessageHandler(messageHandler);

        /**
         * 自定义行为的回调处理，参考文档：高级功能-通知的展示及提醒-自定义通知打开动作
         * UmengNotificationClickHandler是在BroadcastReceiver中被调用，故
         * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
         * */
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
//                if (msg.extra.get("alert").indexOf("贷款") != -1) {//贷款
                if (badgeCount >= 1) {
                    ShortcutBadger.applyCount(context, badgeCount--); //for 1.1.4+
                } else {
                    ShortcutBadger.applyCount(context, 0); //for 1.1.4+
                }
                if (msg.title.indexOf("贷款") != -1) {//贷款
                    if (PreUtils.isLogin(getInstance())) {
                        ActivitySkipUtil.skipAnotherActivityApp(getInstance(), MatchTableActivity.class);
                    } else {
                        ActivitySkipUtil.skipAnotherActivityApp(getInstance(), LoginActivity.class);
                    }
//                } else if (msg.extra.get("alert").indexOf("信用卡") != -1) {//信用卡
                } else if (msg.title.indexOf("信用卡") != -1) {//信用卡
                    if (PreUtils.isLogin(getInstance())) {
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("CompanyID", PreUtils.getCompanyID(getInstance()));
                        map.put("CompanyTypeID", PreUtils.getCompanyTypeID(getInstance()));
                        ActivitySkipUtil.skipAnotherActivityApp(getInstance(), CustomerTableActivity.class, map);
                    } else {
                        ActivitySkipUtil.skipAnotherActivityApp(getInstance(), LoginActivity.class);
                    }
                }
            }
        };
        //使用自定义的NotificationHandler，来结合友盟统计处理消息通知，参考http://bbs.umeng.com/thread-11112-1-1.html
        //CustomNotificationHandler notificationClickHandler = new CustomNotificationHandler();
        mPushAgent.setNotificationClickHandler(notificationClickHandler);


        //注册推送服务 每次调用register都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                UmLog.i("aaa", "device token: " + deviceToken);
                mDeviceToken = deviceToken;
                sendBroadcast(new Intent(UPDATE_STATUS_ACTION));
            }

            @Override
            public void onFailure(String s, String s1) {
                sendBroadcast(new Intent(UPDATE_STATUS_ACTION));
            }
        });
    }

    private ApplicationLike tinkerApplicationLike;
    private void initTinkerPatch(){
        // 我们可以从这里获得Tinker加载过程的信息
        if (BuildConfig.TINKER_ENABLE) {
            tinkerApplicationLike = TinkerPatchApplicationLike.getTinkerPatchApplicationLike();
            // 初始化TinkerPatch SDK
            TinkerPatch.
                    init(tinkerApplicationLike).
                    reflectPatchLibrary().
                    setPatchRollbackOnScreenOff(true).
                    setPatchRestartOnSrceenOff(true).
                    setFetchPatchIntervalByHours(3);
            // fetchPatchUpdateAndPollWithInterval 与 fetchPatchUpdate(false)
            // 不同的是，会通过handler的方式去轮询
            TinkerPatch.with().fetchPatchUpdateAndPollWithInterval();
        }
    }

    /**
     * google analytics
     *
     * @return
     */
    synchronized public Tracker getDefaultTracker() {
        if (mTracker == null) {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
            mTracker = analytics.newTracker("UA-10719358-21");
//            mTracker = analytics.newTracker(R.xml.global_tracker);
        }
        return mTracker;
    }

}
